package com.seckill.Cache;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.seckill.Common.Constant.RedisConstants;
import com.seckill.Model.DO.GoodsSeckill;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 秒杀商品的缓存操作类
 * @author 不鄢
 */
@Component
public class GoodsSecKillCache {

    @Autowired
    private StringRedisTemplate redisTemplate;

    public boolean addSecKill(GoodsSeckill goodsSeckill){
        try {
            String jsonString = JSON.toJSONString(goodsSeckill);
            //防止缓存雪崩 设置过期时间添加随机数，避免同一时间大量key同时过期
            redisTemplate.opsForValue().set(RedisConstants.SECKILL_INFO+goodsSeckill.getGoodsId(),
                    jsonString,30*60*1000+RedisConstants.getRandomNum(), TimeUnit.MILLISECONDS);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean addSecKillList(IPage<GoodsSeckill> goodsSeckillIPage,Integer pageNo,Integer pageSize){
        try {
            String jsonString = JSON.toJSONString(goodsSeckillIPage);
            //防止缓存雪崩
            redisTemplate.opsForValue().set(RedisConstants.SECKILL_LIST_INFO + pageNo + "_" + pageSize
                    , jsonString, 10 * 1000 + RedisConstants.getRandomNum(), TimeUnit.MILLISECONDS);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 创建商品数量，每次预下单从这里库存减一
     * key为秒杀场次id + 商品id 保证唯一性
     * @param goodsSeckill
     */
    public void addToken(GoodsSeckill goodsSeckill){
        redisTemplate.opsForValue().set(RedisConstants.GOODS_STOCK + goodsSeckill.getId() + "_" + goodsSeckill.getGoodsId(),
                goodsSeckill.getStockCount().toString(),60, TimeUnit.HOURS);
    }

    public IPage<GoodsSeckill> getSecKillList(Integer pageNo, Integer pageSize) {
        String secKillJSON = redisTemplate.opsForValue().get(RedisConstants.SECKILL_LIST_INFO + pageNo + '_'  + pageSize);
        //检查是否为空
        if(Strings.isBlank(secKillJSON)){
            return null;
        }
        return JSON.parseObject(secKillJSON,IPage.class);
    }

    public GoodsSeckill getSecKill(Long id) {
        String seckillJSON = redisTemplate.opsForValue().get(RedisConstants.SECKILL_INFO + id);
        if (Strings.isBlank(seckillJSON)){
            return null;
        }
        return JSON.parseObject(seckillJSON, GoodsSeckill.class);
    }
}
